package scau.jump.securitytrace.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import scau.jump.securitytrace.client.ManagerClient;
import scau.jump.securitytrace.dataModel.ProductDataModel;
import scau.jump.securitytrace.init.Init;
import scau.jump.securitytrace.popupwindow.ProductWindow;

import com.securitytrace.model.Product;

public class AddProductButtonListener implements ActionListener {

	private ProductWindow productWindow;
	
	public AddProductButtonListener(ProductWindow productWindow) {
		this.productWindow = productWindow;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		ManagerClient managerClient = productWindow.getManagerClient();
		ProductDataModel productDataModel = managerClient.getProductModel();
		
		String name = productWindow.getProductTextField().getText();
		String desc = productWindow.getProductTextArea().getText();
		if(name.trim().isEmpty()) {
			JOptionPane.showMessageDialog(productWindow, "产品类别不能为空");
		}else if(desc.trim().isEmpty()) {
			JOptionPane.showMessageDialog(productWindow, "产品类别描述不能为空");
		}else {
			Product product = new Product();
			product.setName(name);
			product.setOtherInfo(desc);
			try {
				Init.getProductService().add(product);
				
				int currentPage = productDataModel.getProductCurrenPage();
				int pageSize = managerClient.getPageSize();
				int totalPage = 1;
				
				List<Product> products = new ArrayList<Product>();
				products = Init.getProductService().getListByPage((currentPage-1)* pageSize, pageSize);
				long productNumber = Init.getProductService().getTotalCount();
				if((productNumber % pageSize) == 0) {
					totalPage = (int) (productNumber / pageSize);
				}else {
					totalPage = (int) (productNumber / pageSize) + 1;
				}
				productDataModel.setDataVector(products);
				productDataModel.setProductTotal(totalPage);
				managerClient.getProductPanel().getProductPageInfoLabel().setText(productDataModel.getProductPageInfo());
				productWindow.dispose();
			} catch(Exception ex) {
				JOptionPane.showMessageDialog(productWindow, "操作失败");
			}
		}
	}
}
